<?php
/**
* File that contains FetchController class.
* @package busmap
*/

/**
* FetchController class is responsible for:
* -Generating XML with busstops to be used by Jquery to populate the map.
* -Updating busstop coordinates when a busstop on the map is being directly manipulated by an admin.
* @package busmap
*/
class FetchController extends Zend_Controller_Action
{

	/**
	* This function generates an XML with busstops and buslines going through them.
	* The generated XML will later be read by Ajax when populating the map.
	*/
	public function busstopsAction()
	{
		$this->_helper->layout->disableLayout();

		$blank = <<<XML
<busstops>
</busstops>
XML;
		$xml = new SimpleXMLElement($blank);

		$busStopMapper = new Application_Model_BusStopMapper();
		$busstops = $busStopMapper->fetchAll();
		foreach($busstops as $busstop){
			$busstopNode = $xml->addChild('busstop');
			$busstopNode->addChild('id', $busstop->getId());
			$busstopNode->addChild('name', $busstop->getName());
			$busstopNode->addChild('xCoordinate', $busstop->getXCoordinate());
			$busstopNode->addChild('yCoordinate', $busstop->getYCoordinate());
			$buslinesNode = $busstopNode->addChild('busLines');

			$buslineToBusstopMapper = new Application_Model_BusLineToBusStopMapper();
			$buslines = $buslineToBusstopMapper->findBusLines($busstop->getId());
			foreach($buslines as $busline){
				$buslineNode = $buslinesNode->addChild('busLine');
				$buslineNode->addChild('name', $busline->getName());
				$colorMapper = new Application_Model_ColorMapper();
				$color = new Application_Model_Color();
				$colorMapper->find($busline->getColorId(), $color);
				$buslineNode->addChild('redValue', $color->getRedValue());
				$buslineNode->addChild('greenValue', $color->getGreenValue());
				$buslineNode->addChild('blueValue', $color->getBlueValue());
			}

		}

		$this->view->xmlOutput = $xml->asXml();


	}

	/**
	* This function is called by Ajax when an administrator directly manipulates busstops in the map.
	* It updates the manipulated busstop coordinates and outputs "1" if successful.
	*/
	public function busstopsupdateAction(){
		$this->_helper->layout->disableLayout();
		$userSession = new Zend_Session_Namespace('Auth');
		if($userSession->id){
			$id = intval($_POST['id']);
			$x = intval($_POST['x']);
			$y = intval($_POST['y']);
			if($id && $x && $y){
				$busstop = new Application_Model_BusStop();
				$busstopMapper = new Application_Model_BusStopMapper();
				$busstopMapper->find($id, $busstop);
				$busstop->setId($id)
						->setXCoordinate($x)
						->setYCoordinate($y);
				$busstopMapper->save($busstop);

				echo 1;
			}else{
				echo 0;
			}
		}else{
			echo -1;
		}
	}



}

